package com.manolo.framework.connection.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;

import com.google.gson.Gson;
import com.manolo.framework.connection.entity.Player;

/**
 * 
 */

/**
 * @author gustavo
 * 
 */
public class ServerPlayerSender implements Runnable {

	private PrintWriter out;

	private Integer playerId;

	private HashMap<Integer, Player> players;

	private Socket socket;

	public ServerPlayerSender(Integer id, Socket client,
			HashMap<Integer, Player> message) {

		playerId = id;
		players = message;
		try {
			socket = client;
			this.out = new PrintWriter(client.getOutputStream(), true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void send() {
		if (players.get(playerId) != null) {
			Gson gson = new Gson();
			String json = gson.toJson(players.get(playerId));
			out.println(json);
			players.get(playerId).getMessages().clear();
			// players.get(playerId).getCards().clear();
			players.get(playerId).setHasSendCads(false);

		}

	}

	@Override
	public void run() {
		while (true) {
			if (socket.isClosed()) {
				break;
			} else {

				send();
				try {
					synchronized (players.get(playerId)) {
						players.get(playerId).wait();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

}
